﻿using System;
using System.Windows;
using System.Windows.Input;
using PengSW.WindowHelper;

namespace ProtocolAnalyzer
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            _Model = new AnalyzeModel(this.Dispatcher);
            this.Exec(_Model.Load);
            this.DataContext = _Model;
        }

        private AnalyzeModel _Model;

        private void OnStartListen_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            this.Exec(_Model.StartListen);
        }

        private void OnStartListen_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = _Model?.CanStartListen ?? false;
        }

        private void OnStopListen_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            this.Exec(_Model.StopListen);
        }

        private void OnStopListen_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = _Model?.IsListenning ?? false;
        }

        private void OnCreateConnection_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            this.Exec(_Model.CreateConnection);
        }

        private void OnCreateConnection_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = _Model?.CanCreateConnection ?? false;
        }

        private void OnSend_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            this.Exec(() =>
            {
                _Model.SendTextToCurrentConnection(e.Parameter as string);
            });
        }

        private void OnSend_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = _Model?.CurrentProtocol != null && e.Parameter as string != null;
        }

        private void OnDisconnect_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            this.Exec(_Model.Connections.ActiveItem.Disconnect);
        }

        private void OnDisconnect_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = _Model?.CurrentConnection != null;
        }

        private void OnEditRules_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            RulesEdit aEdit = new RulesEdit(_Model);
            aEdit.ShowDialog();
        }

        private void OnWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            this.Exec(_Model.Save);
        }
    }
}
